<template>
   <div class="container">
      <div class="app-container">
         <div class="left">
            <el-input
               placeholder="请输入内容"
               prefix-icon="el-icon-search"
               size="mini" style="width: 80%;"
               @input="changeStaff"
               v-model="qureyParams.keyword">
            </el-input>
            <!-- 树形组件 -->
             <div class="tree">
               <el-tree 
               :data="dataTree" 
               :props="defaultProps" 
               default-expand-all
               highlight-current
               :expand-on-click-node="false"
               node-key="id"
               ref="deptForm"
               @current-change="selectNode">
            </el-tree>
             </div>
         </div>
         <!-- 又表 -->
         <div class="right">
             <div class="control">
               <el-button type="primary" size="mini" @click="addStaff" v-permission="'add-emplouy'">添加员工</el-button>
               <el-button size="mini" @click="exportList">excle表格导出</el-button>
               <el-button size="mini" @click="importList" v-excel="'excel'">excle表格导入</el-button>
             </div>
             <div class="table">
               <el-table :data="staffList" class="tables" 
               :cell-style="{borderColor:'#dcdfe6'}" 
               :header-cell-style="{borderColor:'#dcdfe6'}"
               :header-row-style="{color:'#000'}"
               :row-style="{height: '50px'}"  
              >
                  <el-table-column label="头像" align="center" prop="staffPhoto">
                     <template v-slot="{row}">
                        <el-avatar :src="row.staffPhoto" v-if="row.staffPhoto" :size="40"></el-avatar>
                        <span class="avatar" v-else>{{ row.username.charAt(0) }}</span>
                     </template>
                  </el-table-column>
                  <el-table-column label="姓名" prop="username" align="center"></el-table-column>
                  <el-table-column label="手机号" sortable prop="mobile" align="center"></el-table-column>
                  <el-table-column label="工号" sortable prop="workNumber" align="center"></el-table-column>
                  <el-table-column label="聘用形式" prop="formOfEmployment" align="center">
                     <template v-slot="{row}">
                         <span v-if="row.formOfEmployment === 1">正式</span>
                         <span v-else-if="row.formOfEmployment===2">非正式</span>
                         <span v-else>无状态</span>
                     </template>
                  </el-table-column>
                  <el-table-column label="部门" prop="departmentName" align="center"></el-table-column>
                  <el-table-column label="入职时间" prop="timeOfEntry" align="center"></el-table-column>
                  <el-table-column label="操作" align="center">
                      <template v-slot="{ row }">
                          <el-button type="text" size="mini" @click="$router.push(`employee/detail/${row.id}`)">查看</el-button>
                          <el-button type="text" size="mini" @click="AssignEmpt(row.id)">角色</el-button>
                          <el-button type="text" size="mini" @click="delStaff(row.id)">删除</el-button>
                      </template>
                  </el-table-column>
               </el-table>
               <!-- 分页 -->
                <el-row type="flex" justify="end" style="height: 60px" align="middle">
                     <el-pagination
                        :page-size = "qureyParams.pagesize"
                        :current-page="qureyParams.page" 
                        layout="total,prev, pager, next"
                        :total="total"
                        @current-change="changePage"
                        background>
                     </el-pagination>
                </el-row>
             </div>
         </div>
      </div>
      <importExcelVue :showDialog.sync="showDialog" @cancellation="cancellation" :getStaffList="getStaffList"></importExcelVue>
      <el-dialog title="分配角色" :visible.sync="showRowDialog">
         <!-- el-checkbox 的 label属性是该 checkbox 对应的值，若该标签中无内容，
          则该属性也充当 checkbox 按钮后的介绍。label与数组中的元素值相对应，如果存在指定的值则为选中状态，否则为不选中。 -->
         <el-checkbox-group v-model="checkList" class="checklist">
           <el-checkbox :label="item.id" v-for="item in rowList" :key="item.id">{{ item.name }}</el-checkbox>
         </el-checkbox-group>   
          <el-row style="width: 100%; height: 50px" type="flex" justify="end" align="middle" slot="footer">
                <el-button type="primary" size="small" @click="isOk">确定</el-button>
                <el-button  size="small" @click="showRowDialog = false">取消</el-button>
            </el-row>
      </el-dialog>
   </div>
</template>

<script>
import { getDepartSerice } from '@/api/department'
import { tranListToTreeData } from '@/utils/index'
import { getStaffService , 
         getExportListService, 
         getDelService, 
         getRoleListService, 
         getInfoService, 
         getStaffRoleService} 
         from '@/api/staff';
import FileSaver from 'file-saver';
import importExcelVue from './compoents/importExcel.vue';
import { Message } from 'element-ui';


export default {
   name: 'Employee',
   components: { importExcelVue },
   data(){
      return {
         // showAddDialog : false, //控制添加员工的弹层
         showDialog: false, //控制导入弹层的显示与隐藏
         total: null, // 分页总数
         staffList: [],
         dataTree: [],
         defaultProps: {
          children: 'children',
          label: 'name'
          },
         qureyParams : {
            departmentId: null,
            page: 1, //请求初始化页面为第一页
            pagesize: 7, //每页有8条数据
            keyword: ''
         },
         showRowDialog: false ,//分配角色弹窗的显示与隐藏
         rowList:[],
         checkList: [],
         currentId: null
      }
   },
   created() {
      this.getTreeList()
      this.getStaffList()
   },
   methods: {
      //  分配角色弹窗的显示与隐藏逻辑
      async AssignEmpt(id){
       const res = await getRoleListService()
       this.rowList = res
       this.currentId = id
       const staff = await getInfoService(id)
       this.checkList = staff.roleIds
       this.showRowDialog = true
      },
      // 分配角色弹窗点击确定按钮
      async isOk(){
         await getStaffRoleService({
            id: this.currentId,
            roleIds: this.checkList
         }),
         Message({ type: 'success', message: '更新角色成功' })
         this.showRowDialog = false
      },
      // 表格分页逻辑
      changePage(newPage){
         // 将新的页码数传过来，复制给之前的页码数
        this.qureyParams.page = newPage
      //   重新发送请求渲染页面
        this.getStaffList()
      },
      // 获取树形控件；列表的逻辑
      async getTreeList() {
        const res =  await getDepartSerice()
        this.dataTree = res
      //   将封装好的树形节点赋值给 空数组，传入第一个参数是一个完整的节点，第二个参数是初始节点 0
        this.dataTree = tranListToTreeData(res, 0)
      //   将 "传智教育" 这个首节点id赋值给 qureyParams.departmentId
        this.qureyParams.departmentId = this.dataTree[0].id
        this.$nextTick(() => {
         // 拿到树形组件中setCurrentKey方法，将记录好的qureyParams.departmentId传过去
          this.$refs.deptForm.setCurrentKey(this.qureyParams.departmentId) //此时一进页面首个节点变为选中状态
        })
      },
      
      // 点击切换拿到方法，更新节点的 id
      selectNode(node){
         this.qureyParams.departmentId = node.id
         // 部门换了,所以页码也要跟着换
         this.qureyParams.page = 1
         this.getStaffList() //调用函数重新渲染
      },
      // 发送请求获取表格数据
      async getStaffList() {
        const res = await getStaffService(this.qureyParams) 
        this.total = res.total
        this.staffList = res.rows
      }  ,
      // 搜索框逻辑
      changeStaff(){
         // 防抖
         clearTimeout(this.timer) //在500毫秒内没输入任何东西先清空定时器
         // 开启定时器
         this.timer = setTimeout(() => {
            this.qureyParams.page = 1 //将页码变为第一页
            this.getStaffList() //重新发送请求获取表格中的数据
         }, 500)
      },
      // 员工列表导出逻辑
     async exportList(){
        const res = await  getExportListService()
      //   下载文件到浏览器
        FileSaver.saveAs(res, '员工列表.xlsx')
      },
      // 员工列表导入逻辑
      importList(){
        this.showDialog = true
      },
      // 员工列表导入弹窗取消按钮
      cancellation(){
         this.showDialog = false
      },
      // 删除员工操作
     async delStaff(id){
        await this.$confirm('确定要永久删除么？？', '温馨提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
      //   如果当前页面数据中只剩1条数据，并且页码数大于1
      if(this.staffList.length === 1 && this.qureyParams.page > 1) this.qureyParams.page--
       await getDelService(id)
       Message({type: 'success' , message: '删除成功'})
       this.getStaffList()
      },
      addStaff(){
         this.$router.push('/employee/detail')
      }
   }
}
</script>

<style scoped>
.app-container{
   display: flex;
}
.left{
   flex: 25%;
   border-right: 1px solid #dcdfe6;
}
.tree{
   margin-left: 40px;
}
.right{
   flex: 70%;
}
.control{
   width: 100%;
   display: flex;
   justify-content: end;
}
.table{
   margin-top: 20px;
   padding: 0 10px;
}
.tables{
   border-bottom: 1px solid #ccc;
}
.avatar{
   display: inline-block;
   width: 40px;
   height: 40px;
   background-color: green;
   text-align: center;
   line-height: 40px;
   color: #fff;
   border-radius: 50%;
}
.checklist{ 
   /* border: 1px solid #000; */
   margin-bottom: 40px;
   height: 100px;
   display: flex;
   flex-wrap: wrap;
   justify-content: space-around;
   align-items: center;
}
</style>